package cn.buhler.jdbc;

import cn.hutool.core.util.StrUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.flume.Context;
import org.apache.flume.conf.ConfigurationException;

/**
 * 从Flume的Context中获取与JDBC相关的配置信息
 * 为其他代码提供HikariDataSource对象，即一个连接池
 */
public class JDBCConfig {

    private String driverClass;
    private String connectionURL;
    private String username;
    private String password;
    private boolean windowsAuthentication;

    public JDBCConfig(Context context) {
        this.driverClass = context.getString("driverClass");
        this.connectionURL = context.getString("url");
        this.username = context.getString("username", "");
        this.password = context.getString("password", "");
        this.windowsAuthentication =   StrUtil.containsAnyIgnoreCase(this.connectionURL,"integratedSecurity=true");
        validateConfig();
    }

    /**
     * 校验JDBC的参数设定
     */
    private void validateConfig() {
        if (StrUtil.isEmpty(connectionURL)) {
            throw new ConfigurationException("url必须指定");
        }

        if (!windowsAuthentication) {
            if (StrUtil.isEmpty(username)) {
                throw new ConfigurationException("如果不是SQLServer的windows 身份认证,必须指定username");
            }
            if (StrUtil.isEmpty(password)) {
                throw new ConfigurationException("如果不是SQLServer的windows 身份认证,必须指定password");
            }
        }

        if (StrUtil.isEmpty(driverClass)) {
            throw new ConfigurationException("必须指定driverClass");
        }
    }

    /**
     * 创建并返回一个JDBC连接池
     * @return
     */
    public HikariDataSource getDataSource() {
        HikariDataSource dataSource = new HikariDataSource();

        dataSource.setJdbcUrl(connectionURL);

        if (!windowsAuthentication) {
            dataSource.setUsername(username);
            dataSource.setPassword(password);
        }

        dataSource.setDriverClassName(driverClass);

        return dataSource;
    }
}
